package me.shurufa.fragments;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.flyco.tablayout.SlidingTabLayout;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import me.shurufa.R;
import me.shurufa.activities.SendBookCommentActivity;
import me.shurufa.bean.Book;
import me.shurufa.utils.Constants;
import me.shurufa.widget.animutils.AnimOnTouchListener;
import me.shurufa.widget.smoothcamera.core.CameraManager;

/**
 * 作者 : andy
 * 日期 : 16/3/8 17:56
 * 邮箱 : andyxialm@gmail.com
 * 描述 :
 */
public class BookDetailFragment extends BaseFragment implements View.OnClickListener {

    @Bind(R.id.tab_layout)
    SlidingTabLayout mTabLayout;
    @Bind(R.id.right_image)
    ImageView mRightIv;
    @Bind(R.id.toolbar_title)
    TextView toolbar_title;
    @Bind(R.id.view_pager)
    ViewPager mViewPager;
    @Bind(R.id.right_image_tmp)
    ImageView mRightIvTmp;

    private List<BaseFragment> mFragmentList;
    private FragmentPagerAdapter mPagerAdapter;
    private PopupWindowClickListener mPopupListener;
    private PopupWindow mPopupWindow; // 用于Toolbar右键点击弹出
    private long mBookId;
    private Book mBook;
    private int mWhereFrom;
    private String mUserId;

    public static BookDetailFragment newInstance(Book book, int whereFrom, String userId) {
        BookDetailFragment fragment = new BookDetailFragment();
        Bundle args = new Bundle();
        args.putSerializable(Constants.ARG_BOOK, book);
        args.putInt(Constants.ARG_FROM_WHERE, whereFrom);
        args.putString(Constants.ARG_USER_ID, userId);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_book_detail, container, false);
        ButterKnife.bind(this, view);
        parseArguments();
        initView();
        return view;
    }

    private void parseArguments() {
        if (getArguments() == null) {
            return;
        }

        mWhereFrom = getArguments().getInt(Constants.ARG_FROM_WHERE);
        mUserId = getArguments().getString(Constants.ARG_USER_ID);
        mBook = (Book) getArguments().getSerializable(Constants.ARG_BOOK);
        if (mBook != null) {
            mBookId = mBook.id;
        }
    }

    private void initView() {
        mPopupListener = new PopupWindowClickListener();
        mRightIv.setVisibility(View.VISIBLE);
        mRightIvTmp.setVisibility(View.INVISIBLE);
        mRightIv.setImageResource(R.drawable.ic_add);
        mRightIv.setOnClickListener(this);
        mRightIv.setOnTouchListener(new AnimOnTouchListener());
        toolbar_title.setText(mBook.title);
        initViewPager();
        mViewPager.setCurrentItem((Constants.TYPE_FRAGMENT_NEWEST_BOOK == mWhereFrom
                || Constants.TYPE_FRAGMENT_MOST_EXCERPT == mWhereFrom
                || Constants.TYPE_FROM_USER_CENTER_DIGEST == mWhereFrom
                || Constants.FROM_MAIN_SEARCH == mWhereFrom)
                   ? 0 : 1);
        if (Constants.FROM_USER_CENTER == mWhereFrom) {
            mViewPager.setCurrentItem(0);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.right_image:
                showPopupWindow();
                break;
        }
    }

    class PopupWindowClickListener implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                // 添加书摘
                case R.id.ll_add_digest:
                    //checkCameraPermission();
                    goCamera();
                    break;

                case R.id.ll_add_comment:
                    Intent in = new Intent(getActivity(), SendBookCommentActivity.class);
                    SendBookCommentActivity.initArguments(in, mBookId, mBook.title);
                    startActivity(in);

                    break;
                case R.id.ll_buy_book:
                    setPagerItem(3);
                    BookInfoFragment bookInfoFragment = (BookInfoFragment) mPagerAdapter.getItem(3);
                    bookInfoFragment.performClickBuyButton();
                    break;
            }
            mPopupWindow.dismiss();
            mPopupWindow = null;
        }
    }

    /**
     * 去相机界面
     */
    private void goCamera() {
        CameraManager.getInstance().openCameraWithBookId(getActivity(), mBookId);
    }

    private void checkCameraPermission() {
        if (Build.VERSION.SDK_INT >= 23) {
            int checkCameraPermission = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA);
            if (checkCameraPermission != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.CAMERA}, Constants.REQUEST_CAMERA);
                return;
            } else {
                goCamera();
            }
        } else {
            goCamera();
        }
    }

    private void initViewPager() {
        mFragmentList = new ArrayList<>();
        mFragmentList.add(BookExcerptFragment.newInstance(mBookId, mBook.title, mWhereFrom, mUserId));
        mFragmentList.add(BookCommentFragment.newInstance(mBookId, mBook.title, mWhereFrom, mUserId));
        mFragmentList.add(CatalogFragment.newInstance(mBookId));
        mFragmentList.add(BookInfoFragment.newInstance(mBookId));

        mPagerAdapter = new FragmentPagerAdapter(getChildFragmentManager()) {
            @Override
            public Fragment getItem(int position) {
                switch (position) {
                    case 0:
                        return mFragmentList.get(0);
                    case 1:
                        return mFragmentList.get(1);
                    case 2:
                        return mFragmentList.get(2);
                    case 3:
                        return mFragmentList.get(3);
                    default:
                        return mFragmentList.get(0);
                }
            }

            @Override
            public int getCount() {
                return 4;
            }

            @Override
            public CharSequence getPageTitle(int position) {
                boolean isFromUserCenter = (Constants.FROM_USER_CENTER == mWhereFrom
                        || Constants.TYPE_FROM_USER_CENTER_DIGEST == mWhereFrom
                        || Constants.TYPE_FROM_USER_CENTER_COMMENT == mWhereFrom);
                switch (position) {
                    case 0:
                        return (isFromUserCenter ? getString(R.string.ta_digest) : getString(R.string.digest) + " " + mBook.excerpt_num);
                    case 1:
                        return (isFromUserCenter ? getString(R.string.ta_comment) : getString(R.string.book_comment) + " " + mBook.comment_num);
                    case 2:
                        return getString(R.string.catalog);
                    case 3:
                        return getString(R.string.book_content_desc);
                    default:
                        return "";
                }
            }
        };
        mViewPager.setOffscreenPageLimit(Integer.MAX_VALUE);
        mViewPager.setAdapter(mPagerAdapter);
        boolean isFromUserCenterComment = (Constants.TYPE_FROM_USER_CENTER_COMMENT == mWhereFrom);
        mTabLayout.setViewPager(mViewPager);

        // 默认tab选中
        setPagerItem(isFromUserCenterComment ? 1 : 0);
    }

    public void setPagerItem(int item) {
        mViewPager.setCurrentItem(item);
        mTabLayout.setCurrentTab(item);
    }

    @Override
    public void onEventMainThread(Intent intent) {
        super.onEventMainThread(intent);

        // 发送完书评 更改数量
        if (Constants.EVENT_SEND_BOOK_COMMENT.equals(intent.getAction())) {
            boolean isFromUserCenter = (Constants.FROM_USER_CENTER == mWhereFrom
                    || Constants.TYPE_FROM_USER_CENTER_DIGEST == mWhereFrom
                    || Constants.TYPE_FROM_USER_CENTER_COMMENT == mWhereFrom);
            mBook.comment_num += 1;
            mTabLayout.getTitleView(1).setText((isFromUserCenter ? getString(R.string.ta_comment) : getString(R.string.book_comment) + " " + mBook.comment_num));
            setPagerItem(1);
        }

        // 删除书评 更改数量
        if (Constants.EVENT_DEL_BOOK_COMMENT.equals(intent.getAction())) {
            boolean isFromUserCenter = (Constants.FROM_USER_CENTER == mWhereFrom
                    || Constants.TYPE_FROM_USER_CENTER_DIGEST == mWhereFrom
                    || Constants.TYPE_FROM_USER_CENTER_COMMENT == mWhereFrom);
            int num = mBook.comment_num;
            num -= 1; // -1
            if (num <= 0) {
                num = 0;
            }
            mBook.comment_num = num;
            mTabLayout.getTitleView(1).setText((isFromUserCenter ? getString(R.string.ta_comment) : getString(R.string.comment)) + " " + mBook.comment_num);
            setPagerItem(1);
        }

        // 删除书摘 更改数量
        if (Constants.EVENT_DEL_BOOK_DIGEST.equals(intent.getAction())) {
            boolean isFromUserCenter = (Constants.FROM_USER_CENTER == mWhereFrom
                    || Constants.TYPE_FROM_USER_CENTER_DIGEST == mWhereFrom
                    || Constants.TYPE_FROM_USER_CENTER_COMMENT == mWhereFrom);
            int num = mBook.excerpt_num;
            num -= 1; // -1
            if (num <= 0) {
                num = 0;
            }
            mBook.excerpt_num = num;
            mTabLayout.getTitleView(1).setText((isFromUserCenter ? getString(R.string.ta_digest) : getString(R.string.digest)) + " " + mBook.excerpt_num);
            setPagerItem(0);
        }
    }

    /**
     * 右上角打开PopupWindow
     * 功能1: 添加书摘
     * 功能2: 添加书评
     * 功能3: 购买书籍
     */
    private void showPopupWindow() {
        // 控件
        LinearLayout llAddDigest;
        LinearLayout llAddComment;
        LinearLayout llBuyBook;

        View contentView = LayoutInflater.from(getActivity()).inflate(R.layout.popupwindow_add, null);
        llAddComment = (LinearLayout) contentView.findViewById(R.id.ll_add_comment);
        llAddDigest = (LinearLayout) contentView.findViewById(R.id.ll_add_digest);
        llBuyBook = (LinearLayout) contentView.findViewById(R.id.ll_buy_book);
        llAddComment.setOnClickListener(mPopupListener);
        llAddDigest.setOnClickListener(mPopupListener);
        llBuyBook.setOnClickListener(mPopupListener);

        mPopupWindow = new PopupWindow(contentView,
                LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT, true);
        mPopupWindow.setTouchable(true);
        mPopupWindow.setTouchInterceptor(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return false;
                // 这里如果返回true的话，touch事件将被拦截
                // 拦截后 PopupWindow的onTouchEvent不被调用，这样点击外部区域无法dismiss
            }
        });

        // 如果不设置PopupWindow的背景，无论是点击外部区域还是Back键都无法dismiss弹框
        // 我觉得这里是API的一个bug
        mPopupWindow.setBackgroundDrawable(getResources().getDrawable(
                R.drawable.ic_popup_shadow_bg));

        // 设置好参数之后再show
        mPopupWindow.showAsDropDown(mRightIvTmp);

    }
}
